#include <QtGui>
#include "grid.h"

Grid::Grid()
{
    // Initial grid setting ///////
    // TODO: load this from a file
    geometry[0] = 200;
    geometry[1] = 200;
    geometry[2] = 400;
    geometry[3] = 200;
    gridWidth = 20;

    CPscalefactor = 1;
    ///////////////////////////////

    gridSize[0] = int(geometry[2] / gridWidth + 0.5);
    gridSize[1] = int(geometry[3] / gridWidth + 0.5);

    squares = new int*[gridSize[0]];
    colors = new int*[gridSize[0]];
    for (int sx = 0; sx < gridSize[0]; sx++)
    {
        squares[sx] = new int[gridSize[1]];
        colors[sx] = new int[gridSize[1]];
        for (int sy = 0; sy < gridSize[1]; sy++)
        {
            squares[sx][sy] = 0;
            colors[sx][sy] = 0;
        }
    }
}

Grid::Grid(int x, int y, int w, int h, int gw)
{
    // Initial grid setting ///////
    // TODO: load this from a file
    geometry[0] = x;
    geometry[1] = y;
    geometry[2] = w;
    geometry[3] = h;
    gridWidth = gw;

    CPscalefactor = 1;
    ///////////////////////////////

    gridSize[0] = int(geometry[2] / gridWidth + 0.5);
    gridSize[1] = int(geometry[3] / gridWidth + 0.5);

    squares = new int*[gridSize[0]];
    colors = new int*[gridSize[0]];
    for (int sx = 0; sx < gridSize[0]; sx++)
    {
        squares[sx] = new int[gridSize[1]];
        colors[sx] = new int[gridSize[1]];
        for (int sy = 0; sy < gridSize[1]; sy++)
        {
            squares[sx][sy] = 0;
            colors[sx][sy] = 0;
        }
    }
}

void Grid::updateSquares()
{
    for (int sx = 0; sx < gridSize[0]; sx++)
    {
        delete [] squares[sx];
        delete [] colors[sx];
        squares[sx] = NULL;
        colors[sx] = NULL;
    }
    delete [] squares;
    delete [] colors;
    squares = NULL;
    colors = NULL;

    printf("new gridwidth = %d\n", gridWidth); fflush(stdout);
    geometry[2] = int(geometry[2] / gridWidth + 0.5) * gridWidth;
    geometry[3] = int(geometry[3] / gridWidth + 0.5) * gridWidth;
    printf("new geom = %d, %d\n", geometry[2], geometry[3]); fflush(stdout);

    gridSize[0] = int(geometry[2] / gridWidth + 0.5);
    gridSize[1] = int(geometry[3] / gridWidth + 0.5);

    squares = new int*[gridSize[0]];
    colors = new int*[gridSize[0]];
    for (int sx = 0; sx < gridSize[0]; sx++)
    {
        squares[sx] = new int[gridSize[1]];
        colors[sx] = new int[gridSize[1]];
        for (int sy = 0; sy < gridSize[1]; sy++)
        {
            squares[sx][sy] = 0;
            colors[sx][sy] = 0;
        }
    }
}
